#!/usr/bin/env python

import os
import subprocess
import sys


SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PATCHES_DIR = os.path.join(SOURCE_ROOT, 'patches')
PATCHES_MAS_DIR = os.path.join(SOURCE_ROOT, 'patches-mas')
SRC_DIR = os.path.join(SOURCE_ROOT, 'src')


def main():
  error = apply_patches_for_dir(PATCHES_DIR)
  if not error:
    if os.environ.has_key('MAS_BUILD'):
      error = apply_patches_for_dir(PATCHES_MAS_DIR)
    if not error:
      return

  sys.stderr.write(error + '\n')
  sys.stderr.flush()
  return 1


def apply_patches_for_dir(directory):
  for root, dirs, files in os.walk(directory):
    prefix = os.path.relpath(root, directory)
    repo = SRC_DIR
    if prefix != '.':
      repo = os.path.join(repo, prefix)
    args = ['git', 'apply', '--ignore-whitespace', '--ignore-space-change',
            '--whitespace', 'fix']
    for name in sorted(files):
      if not name.endswith('.patch'):
        continue
      patch = os.path.join(root, name)
      if subprocess.call(args + [patch], cwd=repo):
        return '{0} failed to apply'.format(os.path.basename(patch))


if __name__ == '__main__':
    sys.exit(main())
